/**
 * @Author: Kindear
 * @Date: 2021-09-05
 * @Desc: 用于查询课表的云函数构建
 */

/**
 * @feature:云函数存在参数不一致的情况 _zc zc week 参数幂等 但是表现形式不一致
 * @Date:2021-09-06
 */

/**
 * @BUG:对于提交的数据要进行表单校验
 * @Date:2021-09-07
 */

/**
 * @Feature:提供全自定义课表形式
 * @Date:2021-09-15
 */
if (!Promise.allSettled) {
    const rejectHandler = reason => ({
        status: "rejected",
        reason
    })
    const resolveHandler = value => ({
        status: "fulfilled",
        value
    })
    Promise.allSettled = promises =>
        Promise.all(
            promises.map((promise) =>
                Promise.resolve(promise)
                .then(resolveHandler, rejectHandler)
            )
            // 每个 promise 需要用 Promise.resolve 包裹下
            // 以防传递非 promise
        );
}
async function execPromise(tasks) {
    return new Promise(function (resolve, reject) {
        Promise.all(tasks).then(res => {
            resolve(res)
            reject(res)
        })
    })
}
async function execPromiseSettled(tasks) {
    return new Promise(function (resolve, reject) {
        Promise.allSettled(tasks).then(res => {
            resolve(res)
            reject(res)
        })
    })
}
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const _ = db.command;
const TIME_TABLE = 'cloud-edu-timetable';
const USER = 'edu-cloud-users'
const timeutil = require('./timeutil');
const formValid = require("./formValidation")
const dayjs = require('dayjs');
const SUMMER_START_DAY = '09-07';
const WINTER_START_DAY = '02-27';
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    let openid = event.openid || wxContext.OPENID;
    let action = event.action;
    /**获取基础的用户信息 */
    let userBase = {}
    let queryRes = await db.collection(USER).where({
        openid
    }).get();
    /**获取用户信息 */
    if (queryRes.data.length == 0) {
        userBase = null;
    } else {
        userBase = queryRes.data[0];
    }
    let nowDate = dayjs();
    /**获取当前年份 */
    let year = dayjs().year();
    console.log(year)
    /**获取当前月份 */
    let month = dayjs().month() + 1;
    console.log(month);
    /**学期 */
    let semester = 1;
    /**构建开学日期 */
    let startDay = ''
    /**获取学年信息 */
    let studyYear = 0
    if (month >= 9 || month < 2) {
        startDay = year + '-' + SUMMER_START_DAY;
        studyYear = parseInt(year)
        semester = 1
    } else if (month >= 2 && month <= 8) {
        startDay = year + '-' + WINTER_START_DAY
        studyYear = parseInt(year) - 1
        semester = 2
    }
    let startDate = dayjs(startDay);
    /**获取相差天数，计算当前周次 */
    let hours = nowDate.diff(startDate, 'hours');
    console.log(hours)
    const days = Math.floor(hours / 24);
    //zc 幂等于 week
    let zc = parseInt(days / 7) + 1;
    switch (action) {
        case 'getUserTable':{
            /**获取该用户全部课表 */
            return await db.collection(TIME_TABLE).where({
                semester: semester,
                year: studyYear,
                openid
            }).limit(100).get();
            break
        }
        case 'queryCommonTable': {
            /**查询公共课表 -- 有学年学期限制 */
            let customQueryRes = await db.collection(TIME_TABLE).where({
                is_first: true,
                semester: semester,
                year: studyYear
            }).get();
            return customQueryRes.data;
            break
        }
        case 'copyTable': {

            /**复制课表 */
            let copyId = event.copyId;
            if (copyId == openid) {
                return {
                    errCode: -1,
                    errMsg: '不能复制自己的课表'
                }
            } else {
                /**先移除之前的课表 */
                await db.collection(TIME_TABLE).where({
                    openid,
                    _updateTime: _.lt(timeutil.TimeCode())
                }).remove();
            }

            let customQueryRes = await db.collection(TIME_TABLE).where({
                openid: copyId
            }).get();

            /**实现promisetasks */
            let promisetasks = []
            let customTable = customQueryRes.data;
            customTable.forEach(function (ele, index) {
                let obj = ele;
                // delete obj.openid
                obj.openid = event.openid;
                /**新增课表内容 */
                obj.action = 'addTable';
                promisetasks.push(cloud.callFunction({
                    name: 'edu-timetable-api',
                    data: {
                        action:'addTable',
                        openid:openid,
                        days: obj.days,
                        start_time: obj.start_time,
                        end_time: obj.end_time,
                        coursename: obj.coursename,
                        teacher:obj.teacher,
                        courselocation:obj.courselocation,
                        weeks: obj.weeks,
                    }
                }))
            })

            let res = await execPromiseSettled(promisetasks);
            console.log(res)
            return res;
            break
        }
        case 'initTable': {
            /**检索自定课表信息 */
            let customQueryRes = await db.collection(TIME_TABLE).where({
                openid,
                year: studyYear,
                semester,
                weeks: zc
            }).get();
            console.log(customQueryRes)
            /**优先检索数据 */
            /**返回请求信息 */
            return {
                errCode: 0,
                currentWeek: zc,
                semester,
                userInfo: userBase,
                timetableData: customQueryRes.data
            }
            break
        }
        case 'queryTable': {
            //周次
            let _zc = event.zc || zc;
            /**检索自定课表信息 */
            /**检索自定课表信息 */
            let customQueryRes = await db.collection(TIME_TABLE).where({
                openid,
                year: studyYear,
                semester,
                weeks: _zc
            }).get();
            console.log(customQueryRes)
            /**优先检索数据 */
            /**返回请求信息 */
            return {
                errCode: 0,
                userInfo: userBase,
                currentWeek: _zc,
                semester,
                timetableData: customQueryRes.data
            }
            break
        }
        case 'deleteCustom': {
            let docId = event.docId;
            return await db.collection(TIME_TABLE).doc(docId).remove();
            break
        }

        case 'addTable': {
            // console.log(openid)
            /**新增课表 */
            console.log(event)
            let weeks = event.weeks;
            let obj = {
                openid,
                year: studyYear,
                semester,
                weeks,
                days: event.days,
                subject_id: parseInt(Math.round(Math.random() * 10000)),
                start_time: event.start_time,
                end_time: event.end_time,
                coursename: event.coursename,
                teacher: event.teacher,
                courselocation: event.courselocation,
                _createTime: timeutil.TimeCode(),
                _updateTime: timeutil.TimeCode()
            }
            let rules = [{
                    name: "weeks",
                    rule: ["required"],
                    msg: ["请选择周次"]
                },
                {
                    name: "days",
                    rule: ["required"],
                    msg: ["请选择星期几"]
                },
                {
                    name: "coursename",
                    rule: ["required"],
                    msg: ["请填写课程名称"]
                },
                {
                    name: "courselocation",
                    rule: ["required"],
                    msg: ["请填写教室名称"]
                },
                {
                    name: "teacher",
                    rule: ["required"],
                    msg: ["请填写教师姓名"]
                }
            ]
            let checkRes = formValid.validation(obj, rules);
            if (event.start_time > event.end_time) {
                checkRes = '时间顺序错误'
            }
            if (!checkRes) {
                /**如果不存在冲突情况 */

                /**判断是否存在相同课程 */
                let courseRes = await db.collection(TIME_TABLE).where({
                    days: event.days,
                    start_time: event.start_time,
                    end_time: event.end_time,
                    coursename: event.coursename,
                    teacher: event.teacher,
                    weeks
                }).get();
                if (courseRes.data.length == 0) {
                    obj.is_first = true
                    return await db.collection(TIME_TABLE).add({
                        data: obj
                    })
                } else {
                    obj.is_first = false
                    return await db.collection(TIME_TABLE).add({
                        data: obj
                    })
                }

            } else {
                return {
                    errCode: -1,
                    errMsg: checkRes
                }
            }
            break
        }
    }
}